<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button :disabled="!checkPermission('importEmployee')" size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="showQRCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="2"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSetting.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>

      <AddEmployee :show-dialog="showDialog" />

      <el-dialog title="头像二维码" :visible="isShowQRCode" @close="isShowQRCode = false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <AssignRole ref="assignRole" :show-dialog.sync="showAssignRole" />
    </div>
  </div>
</template>

<script>
import { getEmployeeApi, delEmployeeApi } from '@/api/employee'
import employeeEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import qrcode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      total: 0,
      pageSetting: {
        page: 1,
        size: 5
      },
      employeeList: [],
      showDialog: false,
      isShowQRCode: false,
      showAssignRole: false
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async assignRole(id) {
      await this.$refs.assignRole.getUserDetail(id)
      this.showAssignRole = true
    },
    showQRCode(url) {
      if (url) {
        this.isShowQRCode = true
        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.myCanvas, url)
        })
      }
    },
    async delEmployee(id) {
      // 二次询问
      await this.$confirm('是否确认删除?')
      // 发请求
      await delEmployeeApi(id)
      // 提醒用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployee()
    },
    async getEmployee() {
      const { rows, total } = await getEmployeeApi(this.pageSetting)
      this.total = total
      this.employeeList = rows.map(user => {
        // 本地数据缺失了账号状态, 临时添加
        return {
          ...user,
          enableState: user.enableState || 1
        }
      })
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getEmployee()
    },
    formatEmployment(row, col, cell) {
      const obj = employeeEnum.hireType.find(item => Number(item.id) === Number(cell))
      return obj ? obj.value : '未知形式'
    },
    async exportExcel() {
      const { rows } = await getEmployeeApi({
        page: 1,
        size: this.total
      })
      // console.log('之前数据', rows)
      // 准备表头
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职日期']
      // 数据转换
      const data = rows.map(user => {
        // 假设有一个函数
        // 可以接受用户对象, 根据表头顺序
        // 转换成数组返回
        return this.convertUserArr(user)
      })
      // console.log('之后数据', data)
      // 生成文件
      export_json_to_excel({
        header,
        data
      })
    },
    convertUserArr(user) {
      const newUser = []
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职日期']
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry'
      }
      // 遍历表头, 按顺序,从用户对象 user 当中取出对应 value 放入数组中
      header.forEach(key => {
        const enKey = dict[key]
        const value = user[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = employeeEnum.hireType.find(item => item.id === value)
          newUser.push(obj ? obj.value : '未知形式')
        } else if (enKey === 'timeOfEntry') {
          newUser.push(formatDate(value))
        } else {
          newUser.push(value)
        }
      })
      return newUser
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 120px;
  object-fit: cover;
}
</style>
